#include "hcpp/ptp2_shadow_table.h"
#include "hcpp/ptp2_log.h"

static class_info_t class_info = {
    .size        = sizeof(ptp2_shadow_table_t),
    .destructor  = NULL,
    .mem_alloc   = NULL,
    .mem_free    = NULL
};

bool
ptp2_shadow_table_init(ptp2_shadow_table_t *this)
{
    object_init(this, &class_info);

    /* set size to zero */
    this->size = 0;

    return true;
}

/**
 * Copy part of node table to a shadow table.
 * Shadow table includes only
 * -
 */
void
ptp2_shadow_table_copy(ptp2_shadow_table_t *this, ptp2_node_table_t *node_table)
{
    uint16_t            idx         = 0;
    uint16_t            idx_lut     = 0;
    uint16_t            idx_shadow  = 0;
    ptp2_lut_entry_t   *lut_entry   = NULL;

    PTP2_LOG_PRINTLN(PTP2_LOG_SHADOW_TABLE, PTP2_LOG_DEBUG, ("idx  lut  shadow"));

    for (idx = 0; idx < node_table->size; idx++) {
        idx_lut   = node_table->idx_table[idx];
        lut_entry = &(node_table->lut_table[idx_lut]);

        if (lut_entry->slave != NULL) {

            PTP2_LOG_IPV4(&(lut_entry->slave->address->ipv4), ipv4_str);
            PTP2_LOG_PRINTLN(PTP2_LOG_SHADOW_TABLE, PTP2_LOG_DEBUG, ("%04u %04u %04u address = %s", idx, idx_lut, idx_shadow, ipv4_str));

            /* copy */
            this->address_table[idx_shadow]           = *(lut_entry->address);
            this->slave_table[idx_shadow]             = *(lut_entry->slave);

            /* reset references */
            this->slave_table[idx_shadow].lut_entry   = NULL;
            this->slave_table[idx_shadow].address     = &(this->address_table[idx_shadow]);

            idx_shadow++;
        }
    }

    this->size = idx_shadow;
}
